import { stringify } from 'query-string';
import { handleHttpResult, handleTimeout } from './requestHandler';
import { API_BASE } from '~/config';
import 'whatwg-fetch';

function get(url, params) {
  const queryParam = stringify(params);
  const concatSymbol = ~url.indexOf('?') ? '&' : '?';
  return fetch(`${API_BASE}${url}${queryParam ? concatSymbol : ''}${queryParam}`, {
    credentials: 'same-origin',
  })
    .then(handleHttpResult)
    .then(handleTimeout);
}

function post(url, data) {
  return fetch(`${API_BASE}${url}`, {
    method: 'post',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    credentials: 'same-origin',
    body: stringify(data),
  })
    .then(handleHttpResult)
    .then(handleTimeout);
}

export default {
  get,
  post,
};
